/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import tal.drivechain.chain.script.ScriptCompiler;

/**
 *
 * @author eisental
 */
public class ShellScriptObject extends CustomShellObject {
    public ShellScriptObject(DriveShell shell) { super("shellScript", "shellScripts", "shell", shell); }

    public void record(String command) throws IllegalArgumentException {
        shell.recordCommands();
        out.println("Recording shell commands...");
    }

    public void erase(String command) throws IllegalArgumentException {
        shell.getRecordedScript();
    }

    public void save(String command) throws IllegalArgumentException {
        command = command.trim();
        try {
            // save shellScript to <filename>
            if (!command.startsWith("to "))
                throw new IllegalArgumentException("Invalid syntax for save shellScript command (should be: save shellScript to <filename> )");


            File file = ScriptCompiler.getScriptFile(command.substring(3), shell.getActiveChain().getScriptFilePath(), true);
            if (file.exists())
                out.println("Overwriting " + file.getCanonicalPath() + ".");
            else out.println("Saving shell script to " + file.getCanonicalPath());
            Writer output = new BufferedWriter(new FileWriter(file));
            try {
                String script = shell.getRecordedScript();
                out.println(script);
                output.write(script);
            }
            finally {
                output.close();
            }
        } catch (IOException ex) {
            throw new IllegalArgumentException("while saving chain: " + ex.getMessage());
        }
    }
}
